
package com.example.message.controller;


import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.api.R;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.message.entity.PersonInfo;
import com.example.message.entity.User;
import com.example.message.service.PersonInfoService;
import com.example.message.service.RoleService;
import com.example.message.service.SysUserService;
import lombok.RequiredArgsConstructor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;

/**
 * @author lengleng
 * @date 2019/2/1
 */
@RestController
@RequiredArgsConstructor
@RequestMapping("/user")
public class UserController {

	private final RoleService roleService;
	private final SysUserService userService;
	private final PersonInfoService personInfoService;
	// 将 yml 中的自定义配置注入到这里
	@Value("${gorit.file.root.path}")
	private String filePath;

	/**
	 * 分页查询用户
	 * @param page 参数集
	 * @param user 查询参数列表
	 * @return 用户集合
	 */
	@GetMapping("/page")
	public R getUserPage(Page page, User user) {
		LambdaQueryWrapper<User> query = new LambdaQueryWrapper<>();
		if (null == user.getUsername()){
			user.setUsername("");
		}
		if (null != user.getRole()){
			return R.ok(userService.page(page, query.eq(User::getRole,user.getRole()).like(User::getUsername,user.getUsername())));
		}
		return R.ok(userService.page(page, query.like(User::getUsername,user.getUsername())));

	}

	/**
	 * 删除用户信息
	 * @param id ID
	 * @return R
	 */
	@DeleteMapping("/{id}")
	public R userDel(@PathVariable Integer id) {
		return R.ok(userService.removeById(id));
	}

	/**
	 * 添加用户
	 * @param user 用户信息
	 * @return success/false
	 */
	@PostMapping
	public R user(@RequestBody User user) {
		return R.ok(userService.save(user));
	}

	/**
	 * 更新用户信息
	 * @param user 用户信息
	 * @return R
	 */
	@PutMapping
	public R updateUser(@RequestBody User user) {
		return R.ok(userService.updateById(user));
	}

	/**
	 * 获取所有角色信息
	 * @param
	 * @return R
	 */
	@GetMapping("/getAllRole")
	public R getAllRole() {
		return R.ok(roleService.getAllRole());
	}


		/**
	 * 根据用户名查询用户信息
	 * @param username 用户名
	 * @return
	 */
	@GetMapping("/login")
	public R user(@RequestParam String username,@RequestParam String password) {
		User condition = new User();
		condition.setUsername(username);
		User u = userService.getOne(new QueryWrapper<>(condition));
		if(u!= null){
			if(password.equals(u.getPassword())){
//				System.out.println("pp1:"+username+"  "+password);
				return R.ok(u);//登陆成功
			}
		}
		return R.failed("账号或密码错误");
	}

	/**保存头像
	 * @param file 文件
	 * @return
	 */
	@PostMapping("/userPic")
	public R listAncestorUsers(HttpServletRequest request, @RequestParam("file") MultipartFile file,
							   @RequestParam("userId")Integer userId,@RequestParam("type")String type) {
		// 时间 和 日期拼接
		String uid = RandomUtil.randomUUID();
		String newFileName = "\\"+uid+"."+type;
		// 得到文件保存的位置以及新文件名
		File dest = new File(filePath + newFileName);
		Logger log = LoggerFactory.getLogger("UserController");
		try {
			// 上传的文件被保存了
			file.transferTo(dest);

			PersonInfo personInfo = new PersonInfo();
			personInfo.setUserId(userId);
			personInfo.setUserPic(uid+"."+type);
			personInfoService.updateById(personInfo);

			// 打印日志
			log.info("上传成功，当前上传的文件保存在 {}",filePath + newFileName);
			// 自定义返回的统一的 JSON 格式的数据，可以直接返回这个字符串也是可以的。
			return R.ok("上传成功");
		} catch (IOException e) {
			log.error(e.toString());
		}
		// 待完成 —— 文件类型校验工作
		return R.failed("上传错误");
	}


	/**获取头像位置
	 * @param
	 * @return
	 */
	@GetMapping("getUserPic")
	public String getUserPic(@RequestParam("userId")Integer userId) {
//		int userId =SecurityUtils.getUser().getId();
		PersonInfo ps = personInfoService.getById(userId);
		System.out.println(ps);
		return ps.getUserPic();
	}

	/**获取用户个人信息
	 * @param
	 * @return
	 */
	@GetMapping("getPersonInfo")
	public R getPersonInfo(@RequestParam("userId") Integer userId) {
//		int userId =SecurityUtils.getUser().getId();
		PersonInfo ps = personInfoService.getById(userId);
//		System.out.println(ps);
		return R.ok(ps);
	}

	/**保存用户个人信息
	 * @param
	 * @return
	 */
	@PutMapping("savePerson")
	public R savePerson(@RequestBody PersonInfo personInfo,@RequestParam Integer userId) {
//		int userId =SecurityUtils.getUser().getId();
		System.out.println(userId+" 保存信息  "+personInfo);
		personInfo.setUserId(userId);
		return R.ok(personInfoService.updateById(personInfo));
	}

	/**
	 * 修改密码
	 * @param
	 * @return R
	 */
	@PutMapping("changePassword/{id}")
	public R changePassword(@PathVariable Integer id,@RequestParam String password,@RequestParam String newpassword2) {
		User u1 =new User();
		u1.setId(id);
		User u = userService.getOne(new QueryWrapper<>(u1));;
		System.out.println(u);
		if(u.getPassword().equals(password)){
			u.setPassword(newpassword2);
			System.out.println(u);
			return R.ok(userService.updateById(u));
		}else {
			return R.failed("原密码错误或其他原因导致修改失败");
		}

	}

}
